package com.dss.auto_deploy.controller;

import com.dss.auto_deploy.constants.AutoConstants;
import com.dss.auto_deploy.domain.AdmDocker;
import com.dss.auto_deploy.domain.Server;
import com.dss.auto_deploy.rabbitmq.DockerDeployMqDto;
import com.dss.auto_deploy.rabbitmq.config.RabbitSender;
import com.dss.auto_deploy.service.IAdmDockerService;
import com.dss.auto_deploy.service.IServerService;
import com.dss.auto_deploy.util.DockerUtil;
import com.dss.auto_deploy.util.RemoteSshUtil;
import com.dss.auto_deploy.util.Result;
import com.dss.auto_deploy.util.StringUtils;
import com.dss.auto_deploy.util.mail.MailUtil;
import com.dss.auto_deploy.util.mail.MyEmail;
import com.dss.auto_deploy.vo.AdmDockerVo;
import com.dss.auto_deploy.vo.MqMsgVo;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.model.Image;
import com.jcraft.jsch.Session;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.mail.MessagingException;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.List;

import static com.dss.auto_deploy.constants.GitlabConstants.DEPLOY_EXCHANGE;


/**
 * @description: 测试控制器
 * @author: dongshoushan
 * @date:2022-11-23 20:55:37
 */
@RestController
@RequestMapping("/test")
@RequiredArgsConstructor(onConstructor = @_(@Autowired))
@Api(tags ="01: 测试")
@Slf4j
public class TestController {
    private final MailUtil mailUtil;
    private final RemoteSshUtil remoteSshUtil;
    private final DockerUtil dockerUtil;
    private final IAdmDockerService admDockerService;
    private final IServerService serverService;
    private final RabbitSender rabbitSender;

    @PostMapping("rabbitSender")
    @ApiOperation(value = "rabbitSender", notes="rabbitSender")
    public Result rabbitSender(@RequestBody DockerDeployMqDto dockerDeployMqDto){
        rabbitSender.sendRabbitMQ(MqMsgVo.builder().exchangeName(DEPLOY_EXCHANGE).data(dockerDeployMqDto).build());
        return Result.success();
    }
    /**
     * @param myEmail 我电子邮件
     * @return {@link Result }
     * @description: 插入
     * @author: dongshoushan
     * @date:2022-11-23 20:55:37
     */
    @PostMapping("sendMail")
    @ApiOperation(value = "发邮件", notes="发邮件")
    public Result insert(@RequestBody @Valid MyEmail myEmail) throws MessagingException, GeneralSecurityException, UnsupportedEncodingException {
        String text = myEmail.getText();
        //String footer = StringUtils.format("<br/><br/><br/><p>         此邮件来自于自动化测试平台。北京地址：<a target='_blank' href='{}'>{}</a>" +
        //        "，若不想再接收此类邮件可以前往个人中心进行取消订阅</p>","http://10.121.138.120:28088","http://10.121.138.120:28088");
        //text+=footer;
        myEmail.setText(text);
        mailUtil.sendMail(myEmail);
        return Result.success("发送成功");
    }


    /**
     * @param imageName 图片名字
     * @param tag       标签
     * @return {@link Result }
     * @description: 测试注册中心
     * @author: dongshoushan
     * @date:2022-11-23 20:55:37
     */
    @GetMapping("testRegistry")
    @ApiOperation(value = "仓库处理", notes="仓库处理")
    public Result testRegistry(String imageName,String tag) throws Exception {
        String getSh256 = StringUtils.format(AutoConstants.GET_REGISTRY_256,"192.168.29.180","5000",imageName,tag);
        Server server = serverService.getServerByIp("192.168.29.180");
        Session session = remoteSshUtil.connect(server);
        String exec = remoteSshUtil.exec(getSh256, session);
        String[] split = exec.split("\r\n");
        String code = split[0];
        if (code.contains("200")){
            String sh256 = split[3];
            sh256 = sh256.replace("Docker-Content-Digest: ","");
            System.out.println(sh256);
            String s1 = StringUtils.format(AutoConstants.DEL_REGISTRY, server.getIp(),"5000",imageName, sh256);
            remoteSshUtil.exec(s1, session);
            //gc
            remoteSshUtil.exec(AutoConstants.GARBAGE_COLLECTION, session);
        }else if (code.contains("404")) {
            System.out.println("未找到");
        }else {
            System.out.println(exec);
        }
        return Result.success();
    }


    @GetMapping("getContainerListByNameLike")
    @ApiOperation(value = "查询docker镜像名称", notes="查询docker镜像名称")
    public Result getContainerListByNameLike(String imageName,String ip){
        AdmDocker admDocker = admDockerService.getByIp(ip);
        AdmDockerVo admDockerVo = admDockerService.getVoById(admDocker.getId());
        DockerClient dockerClient = dockerUtil.getDockerClientByDocker(admDockerVo);
        List<Image> images = dockerUtil.getImageNameListByName(dockerClient, imageName);
        System.out.println(images);
        return Result.success();
    }

}
